import type { BaseResponse } from "@/api/response";
import { http } from "@/utils/http";
import qs from "qs";

export class Prometheus {
  prometheusUrl = cluster_name => {
    return `/api/v1/proxy/${cluster_name}/k8s/apis/monitoring.coreos.com/v1/prometheuses`;
  };
  prometheusMetricsUrl = (
    cluster_name,
    namespace,
    prometheus_service_name,
    prometheus_prefix,
    prometheus_service_port
  ) => {
    return `/api/v1/proxy/${cluster_name}/k8s/api/v1/namespaces/${namespace}/services/${prometheus_service_name}:${prometheus_service_port}/proxy${prometheus_prefix}api/v1/query_range`;
  };
  /*获取已部署的prometheus服务器*/
  listPrometheuses(cluster_name): BaseResponse<any> {
    let url = this.prometheusUrl(cluster_name);
    const param = {};
    return http.get(url, param);
  }

  /*获取容器指标（mem and fs）*/
  getContainerMetricsMemAndFs(args: {
    cluster_name?: string;
    namespace?: string;
    prometheus_service_name?: string;
    prometheus_prefix?: string;
    prometheus_service_port?: number;
    pod_namespace?: string;
    pod_name?: string;
    container_name?: string;
    secs?: number;
  }) {
    let url = this.prometheusMetricsUrl(
      args.cluster_name,
      args.namespace,
      args.prometheus_service_name,
      args.prometheus_prefix,
      args.prometheus_service_port
    );
    const startTimestamp = Math.floor(Date.now() / 1000) - args.secs; // Unix timestamp for 30 minutes ago
    const endTimestamp = Math.floor(Date.now() / 1000); // Current Unix timestamp
    const param = {
      query: `{__name__=~"container_fs_usage_bytes|container_memory_working_set_bytes",namespace="${args.pod_namespace}",pod="${args.pod_name}",container="${args.container_name}"}`,
      start: startTimestamp,
      end: endTimestamp,
      step: "1m"
    };
    return http.get(url + "?" + qs.stringify(param), {});
  }
  /*获取容器指标（mem and fs）*/
  getContainerMetricsCpu(args: {
    cluster_name?: string;
    namespace?: string;
    prometheus_service_name?: string;
    prometheus_prefix?: string;
    prometheus_service_port?: number;
    pod_namespace?: string;
    pod_name?: string;
    container_name?: string;
    secs?: number;
  }) {
    let url = this.prometheusMetricsUrl(
      args.cluster_name,
      args.namespace,
      args.prometheus_service_name,
      args.prometheus_prefix,
      args.prometheus_service_port
    );
    const startTimestamp = Math.floor(Date.now() / 1000) - args.secs; // Unix timestamp for 30 minutes ago
    const endTimestamp = Math.floor(Date.now() / 1000); // Current Unix timestamp
    const param = {
      query: `sum(irate(container_cpu_usage_seconds_total{namespace="${args.pod_namespace}",pod="${args.pod_name}",container="${args.container_name}"}[5m]))`,
      start: startTimestamp,
      end: endTimestamp,
      step: "1m"
    };
    return http.get(url + "?" + qs.stringify(param), {});
  }
}
